package com.imooc.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imooc.mall.entity.User;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.mapper.UserMapper;
import com.imooc.mall.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.mall.util.MD5Utils;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhaoJianHui
 * @since 2025-05-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User register(String userName, String password) throws ImoocMallException {
        //查询用户名是否已存在，不允许重复
        // 组装查询条件，查询用户名
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        // 执行查询
        User user = getOne(queryWrapper);
        if (user != null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTS);
        }
        //写到数据库
        User newUser = new User();
        newUser.setUsername(userName);
        try {
            newUser.setPassword(MD5Utils.getMD5(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        boolean save = save(newUser);
        if (!save) {
            throw new ImoocMallException(ImoocMallExceptionEnum.REGISTER_FAILED);
        }
        return newUser;
    }

    @Override
    public User login(String userName, String password) throws ImoocMallException {
        String md5Password = null;
        //密码加密
        try {
            md5Password= MD5Utils.getMD5(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //查询用户名是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        queryWrapper.eq("password", md5Password);
        User user = getOne(queryWrapper);
        if (user == null) {
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_PASSWORD);
        }

        return user;
    }

    @Override
    public void updateInfo(User user) throws ImoocMallException {
        //更新用户信息
        boolean update = updateById(user);
        if (!update) {
            throw new ImoocMallException(ImoocMallExceptionEnum.USER_UPDATE_FAILED);
        }
    }

    /**
     * 判断是否是管理员
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        if (user == null) {
            return false;
        }
        //管理员的id是1
        return user.getRole() == 2;
    }
}
